<template>
  <span class="CaseModal">
<!--    <el-button type="text" @click="handleTitle">{{ btnTitle }}</el-button>-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false" append-to-body>
      <el-form ref="caseForm" :model="caseForm" :rules="rulesCaseForm">
        <el-form-item label="用例集名称" :label-width="formLabelWidth" prop="testSuiteName">
          <el-input v-model="caseForm.testSuiteName" autocomplete="off" placeholder="请输入用例集名称"></el-input>
        </el-form-item>
        <el-form-item label="用例集目录" :label-width="formLabelWidth" prop="dirName">
          <TreeSelect :options="cardTree"
                      :multiple="true"
                      :flat="true"
                      placeholder="请选择目录"
                      :normalizer="normalizer"
                      v-model="caseForm.dirName" />
        </el-form-item>
        <el-form-item label="需求名称" :label-width="formLabelWidth" prop="requirementId">
          <el-input v-model="caseForm.requirementId" autocomplete="off" placeholder="关联需求"></el-input>
        </el-form-item>
        <el-form-item label="用例描述" :label-width="formLabelWidth" prop="description">
          <el-input v-model="caseForm.description" autocomplete="off" placeholder="描述用例" type="textarea"  autosize></el-input>
        </el-form-item>
      </el-form>
      <el-row v-show="operate === 'add'">
        <el-col :span="4">
          导入用例文件：
        </el-col>
        <el-col :span="8">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            accetpt=".xlsx,.xls,.xmind"
            :on-remove="handleRemove"
            :on-preview="handlePreview"
            :on-change="handleOnChange"
            :file-list="fileList"
            :auto-upload="false"
            :before-upload="beforeUpload"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">温馨提示：只能上传xmind/excel文件， excel请按照
              <a href='/static/testcase-template.xlsx' style="color: green; font-size: 16px"
                 download="testcase-template.xlsx"> 模板 </a>填写...</div>
          </el-upload>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button size="small"  @click="handleCancel"> 取 消 </el-button>
<!--        "dialogFormVisible = false"-->
        <el-button  size="small"  type="primary" :loading="uploading"  @click="handleOK"> 确 定 </el-button>
      </div>
    </el-dialog>
  </span>
</template>

<script>
import request from '@/utils/axios'
import './index.scss'
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import getQueryString from '@/utils/getCookies';
const getCookies = getQueryString.getCookie;
const initData = `{"root":{"data":{"id":"bv8nxhi3c800","created":1562059643204,"text":"中心主题"},"children":[]},"template":"default","theme":"fresh-blue","version":"1.4.43","base":0}`;
export default {
  name: 'CaseModal',
  components: { TreeSelect },
  props: {
    title: {
      type: String,
      default: ''
    },
    operate: {
      type: String,
      default: 'edit'
    },
    productId: {
      type: String,
      default: '1'
    }
  },
  data() {
    return {
      fileList: [],
      fd: '',
      cardTree: ['-1'],
      uploading: false,
      bizIds: '',
      caseId: 0,
      dialogFormVisible: false,
      caseForm: {
        testSuiteName: '',
        dirName: null,
        requirementId: '',
        description: '请描述用例用途'
      },
      rulesCaseForm: {
        testSuiteName: [
          { required: true, message: '请填写用例集名称', trigger: 'blur' },
        ],
        dirName: [
          { required: true, message: '请输入归档目录', trigger: 'change' }
        ]
      },
      formLabelWidth: '120px'
    };
  },
  methods: {
    showDialog: function (index=0, row={}) {
      this.caseId = row.id
      this.getCardTree()
      this.dialogFormVisible = true;
      if (this.operate !== 'add') {
        this.getDetailById()
      }
    },
    // 上传文件之前的钩子：判断上传文件格式、大小等，若返回false则停止上传
    beforeUpload(file) {
      // 文件大小限制为100M
      const fileLimit = file.size / 1024 / 1024 < 100;
      if (!fileLimit) {
        this.$message.error("上传文件大小不超过100M！");
      }
      return false;
    },
    handleCancel() {
      this.fileList = []; // 清空选择的文件列表
      this.dialogFormVisible = false
    },
    handleOK() {
      // 只要不是编辑用例属性，都需要保存脑图
      if (this.operate !== 'edit') {
        this.$refs.caseForm.validate((valid) => {
          if (valid) {
            this.saveEditerData(this.caseForm);
          }
        });
      } else {
        this.$refs.caseForm.validate((valid) => {
          if (valid) {
            this.renameOK(this.caseForm);
          }
        });
      }
      this.dialogFormVisible = false
      this.$emit('getCaseList')
    },
    saveEditerData(values) {
      let requirementId = values.requirementId;
      let params = {
        productLineId: Number(this.$route.params.productLineId),
        creator: getCookies('username'),
        caseType: 0,
        caseContent: initData,
        title: values.testSuiteName,
        channel: 1,
        bizId: values.dirName ? values.dirName.join(',') : '-1',
        id: this.operate !== 'add' ? this.caseId : '',
        requirementId,
        description: values.description,
      };

      // 判断是否上传了用例集文件
      let caseFile = this.operate === 'add'? (this.fd !=='' ? this.fd.get('file'): '') :''

      let url = `/case/create`;
      if (caseFile) {
        if (/(?:xmind)$/i.test(caseFile.name)) {
          url = `/file/import`;
        } else if (/(?:xls|xlsx)$/i.test(caseFile.name)) {
          url = `/file/importExcel`;
        }

        params = new FormData();
        params.append('file', caseFile);
        params.append('creator', getCookies('username'));
        params.append('title', values.testSuiteName);
        params.append('productLineId', this.$route.params.productLineId);
        params.append('requirementId', requirementId);

        params.append('description', values.description);
        params.append('channel', '1');
        params.append('bizId', values.dirName ? values.dirName.join(',') : '-1');
      }
      request(url, {method: 'POST', body: params}).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: this.operate === 'add'
              ? '新建测试用例集成功'
              : '复制测试用例集成功',
          });
          this.$emit('getDirList')
          if (this.operate === 'add') {
            let urls = `/case/edit/${this.$route.params.productLineId}/${res.data}`;
            console.log('跳转的路由url：', urls)
            this.$router.push(urls);
          }
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      });
    },
    renameOK(values) {
      console.log('values: ', values)
      let params = {
        title: values.testSuiteName,
        id: this.caseId,
        requirementId: values.requirementId,
        caseType: 0,
        description: values.description,
        modifier: getCookies('username'),
        bizId: values.dirName ? values.dirName.join(',') : '-1',
        channel: 1,
      };
      let url = '/case/edit';
      request(url, {method: 'POST', body: params}).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '更新成功'
          });
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      });
    },
    handleRemove(file, fileList) {
      console.log('handle remove:', file, fileList);
    },
    handlePreview(file) {
      console.log('handle Preview:', file);
    },
    handleOnChange(file, fileList) {
      this.fileList = [file];
      let fd = new FormData();
      fd.append("file", file.raw);
      this.fd = fd;
    },
    getCardTree: function () {
      const url = '/dir/cardTree'
      request(url, {
        method: 'GET',
        params: {
          productLineId: this.$route.params.productLineId,
          channel: 1,
        },
      }).then(res => {
        this.cardTree = res.data ? res.data.children : [];
      });
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.text,
        children: node.children,
      }
    },
    getDetailById: function () {
      const url = '/case/detail'
      request(url, {
        method: 'GET',
        params: {
          caseId: this.caseId,
        },
      }).then(res => {
        if (res.code === 200) {
          // 下拉树形选项，取对应的选项的id，传给v-model绑定对象，根据id反查text值，才不会出现选项后面跟(unknown)的问题
          const bizIds = res.data.biz.map(item => {
            return item.bizId
          })
          if (this.operate === 'edit') {
            this.caseForm.testSuiteName = res.data.title
          } else {
            this.caseForm.testSuiteName = 'copy of ' + res.data.title
          }
          this.caseForm.dirName = bizIds
        }
      })
    }
  }
}

</script>

<style lang="scss" scoped >
.el-row {
  margin-bottom: 20px
}
</style>
